import cocos
from cocos.director import director
from cocos.actions import *

from config import current as conf

class MessagesLayer(cocos.layer.Layer):
    """A simple status bar with an internal message queue"""
    def __init__(self):
        super(MessagesLayer, self).__init__()
        self.queue = []

        w,h = director.get_window_size()
        self.bg = cocos.layer.ColorLayer(0,0,0,0)
        self.bg.position = 0, 15 - h/2
        self.add(self.bg)

        self.label = cocos.text.Label(" ",
            font_name=conf.body_font, font_size=10, x=15, y=5,
            color=(255, 255, 255, 255), anchor_x='left', anchor_y='bottom')
        self.add(self.label)
        self.playing = False

    def show(self, text):
        """show some text (or queue it up for later display)"""
        self.queue.insert(0, text)
        if not self.playing:
            self._show_next()

    def show_action(self, text):
        """Show method as a cocos2d action"""
        return CallFunc(lambda: self.show(text))

    def action(self):
        """A simple scrolling/fading effect"""
        return FadeIn(.5) + Delay(3.25) + Accelerate(MoveBy((0,-50), .5) | FadeOut(.5))

    def _show_next(self):
        if self.queue:
            self.playing = True
            self.bg.do(FadeTo(230, .5))
            next = self.queue.pop()
            self.label.element.text = next
            self.label.do(Show())
            self.label.do(
                self.action() +
                Hide() + Place((0,0)) + # reset position and hide
                CallFunc(lambda: self._show_next())) # check for next msg
        else:
            self.playing = False
            self.bg.do(FadeOut(.5))